﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Maniac
{
    public class YahooDataDownloader : PriceDataDownloader
    {
        public YahooDataDownloader()
        {
        }

        public override void DownloadPrices(DateTime fvdStartDate)
        {
            System.Net.WebClient wc = new System.Net.WebClient();

            //In implementation, webclient must be async. Proper impl
            // will allow cancel.
            //wc.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(wc_DownloadDataCompleted);
            /* Yahoo symbols:
             * s = symbol (i.e. INTC)
             * d = current month, 0 based integer (December is 11)
             * e = current day integer
             * f = current year
             * g = d
             * a = historical month, 0 based integer (July is 6)
             * b  = historical day, integer 9
             * c = historical year 1986
             * ignore = .csv
             * */
            string sUrl;
            sUrl = "http://ichart.finance.yahoo.com/table.csv?g=d&ignore=.csv";
            sUrl += "&s=" + base.Security.Symbol;
            sUrl += "&d=" + (DateTime.Now.Month - 1);
            sUrl += "&e=" + DateTime.Now.Day;
            sUrl += "&f=" + DateTime.Now.Year;
            sUrl += "&a=" + (fvdStartDate.Month - 1);
            sUrl += "&b=" + fvdStartDate.Day;
            sUrl += "&c=" + fvdStartDate.Year;

            System.Uri tvUri = new Uri(sUrl);

            try
            {
                byte[] data = wc.DownloadData/*Async*/(tvUri);
                /*}

                void wc_DownloadDataCompleted(object sender, System.Net.DownloadDataCompletedEventArgs e)
                {
                    //After downloading, these prices need to be inserted into the Security.HistoricalPrices collection.
            
                        if (!e.Cancelled && e.Error == null)
                        {
                            byte[] data = (byte[])e.Result;
                  */
                /*string textdata = System.Text.Encoding.UTF8.GetString(data);

                string[] lines = textdata.Split(new char[] { '\n' });

                int tviLastYear = 0;
                int tviSessionID = -1;

                for (int i = 1; i < lines.Length; i++)
                {
                    if (lines[i].Length < 1)
                        continue;
                    string[] parts = lines[i].Split(new char[] { ',' });
                    string[] dateparts = parts[0].Split(new char[] { '-' });

                    HistoricalPrice tvHist = new HistoricalPrice();

                    tvHist.Year = Convert.ToInt32(dateparts[0]);
                    tvHist.Month = Convert.ToInt32(dateparts[1]);
                    tvHist.Day = Convert.ToInt32(dateparts[2]);

                    tvHist.Date = new DateTime(tvHist.Year, tvHist.Month, tvHist.Day);

                    HistoricalPrice tvhReturn = base.Security.HistoricalPrices.Find(
                         delegate(HistoricalPrice tvhPrice)
                         {
                             return ((tvhPrice.Year == tvHist.Year) &&
                                 (tvhPrice.Month == tvHist.Month) &&
                                 (tvhPrice.Day == tvHist.Day));
                         }
                     );
                    if (tvhReturn != null)
                        continue;

                    tvHist.OpenPrice = Convert.ToDecimal(parts[1]);
                    tvHist.HighPrice = Convert.ToDecimal(parts[2]);
                    tvHist.LowPrice = Convert.ToDecimal(parts[3]);
                    tvHist.ClosePrice = Convert.ToDecimal(parts[4]);
                    tvHist.CloseAdjustedPrice = Convert.ToDecimal(parts[6]);
                    tvHist.Volume = Convert.ToInt64(parts[5]);
                    tvHist.Symbol = base.Security.Symbol;

                    //trying to get the prior closing value
                    if (i < (lines.Length - 2))
                    {
                        string[] nextPart = lines[i + 1].Split(new char[] { ',' });

                        tvHist.PriorClosePrice = Convert.ToDecimal(nextPart[4]);
                    }
                    else
                    {
                        tvHist.PriorClosePrice = 0;
                    }

                    //is this a new year?
                    if (tviLastYear != tvHist.Year)
                    {
                        tviLastYear = tvHist.Year;
                        tviSessionID = -1;
                    }
                    tviSessionID++;

                    tvHist.Session = tviSessionID;

                    base.Security.HistoricalPrices.Add(tvHist);
                 * */
                //base.Security.LoadPrices(data);
                base.Security.persistSave2(data);
                base.Security.persistLoad2();
                
                EventArgs tvArg = new EventArgs();
                OnDownloadPricesCompleted(tvArg);
            }
            catch (System.Net.WebException wex)
            {
                //probs
                System.Windows.Forms.MessageBox.Show("An error has occurred. Please ensure the symbol you have entered is valid. " + wex.Message, "Maniac Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
            }
        }
        //}

    }

    public class YahooDateDownloader : DateDataDownloader
    {
        public YahooDateDownloader()
        {
        }

        public override void DownloadDates()
        {
            System.Net.WebClient wc = new System.Net.WebClient();

            //In implementation, webclient must be async. Proper impl
            // will allow cancel.
            //wc.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(wc_DownloadDateCompleted);
            /* Yahoo symbols:
             * s = symbol (i.e. INTC)
             * d = current month, 0 based integer (December is 11)
             * e = current day integer
             * f = current year
             * g = d
             * a = historical month, 0 based integer (July is 6)
             * b  = historical day, integer 9
             * c = historical year 1986
             * ignore = .csv
             * */
            string sUrl;
            sUrl = "http://finance.yahoo.com/d/quotes.csv?f=qr1";
            sUrl += "&s=" + base.Security.Symbol;

            System.Uri tvUri = new Uri(sUrl);

            byte[] data = wc.DownloadData(tvUri);
        /*}
        
        void wc_DownloadDateCompleted(object sender, System.Net.DownloadDataCompletedEventArgs e)
        {
            //After downloading, these prices need to be inserted into the Security.HistoricalPrices collection.
            try
            {
                if (!e.Cancelled && e.Error == null)
                {        
        
              byte[] data = (byte[])e.Result;
         */
                    string textdata = System.Text.Encoding.UTF8.GetString(data);

                    DateTime tvdMonthTest = new DateTime(2010,1,1);

                    string[] lines = textdata.Split(new char[] { '\n' });

                    for (int i = 0; i < lines.Length; i++)
                    {
                        if (lines[i].Length < 1)
                            continue;
                        string[] parts = lines[i].Split(new char[] { ',' });
                        for (int y = 0; y < parts.Length;y++ )
                        {
                            if ((parts[y]=="\"N/A\"\r")||(parts[y]=="\"N/A\""))
                                continue;
                            string tvsMonth = parts[y].Substring(1, 3);
                            string tvsDay = parts[y].Substring(5,2);
                            int tviMonth;
                            for (tviMonth = 0; tviMonth < 12; tviMonth++)
                            {
                                if (tvsMonth == tvdMonthTest.ToString("MMM"))
                                    break;
                                else
                                    tvdMonthTest = tvdMonthTest.AddMonths(1);

                            }
                            tviMonth++;
                            DateTime tvdDate;
                            try
                            {
                                tvdDate = new DateTime(DateTime.Now.Year, tviMonth, Convert.ToInt32(tvsDay));
                            }
                            catch (FormatException fex)
                            {
								continue;
                            }
                            catch (ArgumentOutOfRangeException exrng)
                            {
                                continue;
                            }
                            
                            SecurityKeyDate tvsItem = new SecurityKeyDate();
                            tvsItem.KeyDate = tvdDate;
                            if (y == 0)
                            {
                                tvsItem.KeyDateType = SecurityKeyDateType.ExDividend;
                                tvsItem.DayIcon = Properties.Resources.date_error;
                            }
                            else
                            {
                                tvsItem.KeyDateType = SecurityKeyDateType.DividendPayout;
                                tvsItem.DayIcon = Properties.Resources.money;
                            }
                            base.Security.KeyDates.Add(tvsItem);
                        }


                    
                    EventArgs tvArg = new EventArgs();
                    OnDownloadDatesCompleted(tvArg);
                }
           /* }
            catch (Exception ex)
            {
            }*/

        }

    }
}
